"""Configuration loader utilities for DYVA.

- Safe YAML loading with type hints.
- Access helpers for API timeouts and frame sampling.
- Follows project rules: PEP8, type annotations, docstrings, logging.
"""
from __future__ import annotations

import logging
from typing import Any, Dict, Optional
from pathlib import Path

import yaml

LOGGER = logging.getLogger(__name__)


def load_yaml(path: str | Path) -> Dict[str, Any]:
    """Load a YAML file safely.

    Args:
        path: Path to YAML file.

    Returns:
        Parsed dictionary.
    """
    p = Path(path)
    with p.open("r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}


def load_config(config_path: str = "config/config.yaml") -> Dict[str, Any]:
    """Load main configuration.

    Args:
        config_path: Path to config YAML.

    Returns:
        Configuration dictionary.
    """
    cfg = load_yaml(config_path)
    LOGGER.debug("Config loaded from %s", config_path)
    return cfg


def get_api_timeout(cfg: Dict[str, Any], service: str) -> Optional[int]:
    """Get timeout seconds for an API service (deepseek or vlm)."""
    apis = cfg.get("processing", {}).get("apis", {})
    svc = apis.get(service, {})
    return svc.get("timeout_seconds")


def get_frame_sampling_config(cfg: Dict[str, Any]) -> Dict[str, Any]:
    """Return frame sampling configuration for VLM.

    Structure:
        {
            "strategy": str,
            "interval_seconds_default": int,
            "caps_by_duration": {"le_15s": int, ...},
            "global_max_frames": int,
        }
    """
    vlm = cfg.get("processing", {}).get("apis", {}).get("vlm", {})
    fs = vlm.get("frame_sampling", {})
    # Provide sane defaults to avoid KeyError
    return {
        "strategy": fs.get("strategy", "duration_weighted"),
        "interval_seconds_default": fs.get("interval_seconds_default", 5),
        "caps_by_duration": fs.get(
            "caps_by_duration",
            {"le_15s": 5, "le_60s": 10, "le_300s": 15, "gt_300s": 20},
        ),
        "global_max_frames": fs.get("global_max_frames", 4),
    }
